<?php


namespace app\api\model;

use app\api\controller\Code;
use think\Db;
use think\Model;

/**
 * 病例
 * Class CaseModel
 * @package app\api\model
 *
 */
class CaseModel extends Model
{

    /**
     * 设置表名
     * @var string
     */
    protected $table = 'ah_case';

    /**
     *
     * 病例列表
     */
    public static function caseList($params){

        $where = [];
        #关键字搜索
        if (isset($params['keywords']) && $params['keywords'] != ''){

            $where[] = ['name|illness_info','like',"%{$params['keywords']}%"];
        }

        return self::where(['user_id'=>$params['user_id']])
            ->where($where)
            ->field('id,name,sex,age,illness_info,create_at')
            ->order('id desc')
            ->select()->each(function ($item){

                $item['create_at'] = date('Y年m月d日',strtotime($item['create_at']));
            });

    }

    /**
     *
     * 添加档案信息
     */
    public static function caseAdd($params){

        $case = [

            'user_id' => $params['user_id'],
            'name' => $params['name'],
            'sex'  => $params['sex'],
            'age'  => $params['age'],
//            'doctor_name'  => $params['doctor_name'],
//            'inquiry_at'  => $params['inquiry_at'],
            'case_imgs'  => json_encode($params['case_imgs']),
            'inspect_imgs'  => $params['inspect_imgs'],
            'illness_info'  => $params['illness_info'],
            'update_at'  => time(),
        ];
        if (isset($params['id']) && $params['id'] > 0){

            return self::where(['id'=>$params['id']])->update($case);
        }

        return self::insert($case);


    }

    /**
     *
     * 病例的详情
     */
    public static function caseInfo($id){

        $data = self::where(['id'=>$id])->find();
        #病例图片
        if ($data['case_imgs']){

            $data['case_imgs'] = json_decode($data['case_imgs'],true);
        }

        #检测报告图片
        if ($data['inspect_imgs']){

            $data['inspect_imgs'] = explode('|',$data['inspect_imgs']);
        }

        #随访记录
        $data['follow_record'] = FollowRecordModel::where(['case_id'=>$id])
            ->field('id,visit_at,inspect_imgs,visit_info,create_at')
            ->order('id desc')
            ->select()
            ->toArray();
        return $data;
    }



}